/**
 * Created by xmgong on 2017/10/24.
 * 账号编辑
 */
import React from 'react';
import {
	connect
} from 'react-redux';
import {
	Text,
	ScrollView,
	View,
	StyleSheet,
	TouchableOpacity,
	Image,
	Button,
	TextInput,
	TouchableHighlight,
	NativeModules,
	InteractionManager,
	Alert
} from 'react-native';
import {
	showLoading,
	hideLoading,
	toast,
	chooseLocation,
	ChooseCity
} from '../../utils/NativeUtil';
import commonStyles from './styles';
import {
	getCodeAction,
	saveBankInfoAction,
	BankInfoCheckAction
} from './actions';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import {
	naviPush,
	naviBack
} from '../../navigatorApp/actions';
import {
	BackCardUtil,
	PhoneUtil
} from '../../utils/common';


class AccountEdit extends React.Component {

	static navigationOptions = ({
		navigation,
		screenProps
	}) => ({
		header: <CLNavigatorHeader navigation={navigation} title="编辑"/>,
	});

	constructor(props) {
		super(props);
		this.codeTime = 120;
		this.timer = null;
		this.codeEnable = true;
		this.flag = props.navigation.state.params.flag;
		this.bankid = this.initBankId();
		this.state = {
			accounttype: '银行卡',
			bankname: this.props.bankName != undefined && this.props.bankName.length == 0 ? "点击获取开户银行" : this.props.bankName,
			bankarea: this.props.bankArea != undefined && this.props.bankArea.length == 0 ? "开户地址" : this.props.bankArea,
			code: '',
			bankid: this.bankid,
			savesecond: '发送验证码',
			carderror: this.initBankError(),
		};
	}


	initBankId = () => {
		let card = "";
		let id = this.props.bankId;
		let tmp = id.replace(/\D/g, "");
		for (let i = 0; i < tmp.length; i++) {
			if (i % 4 === 0 && i > 0) {
				card += "  " + tmp.charAt(i);
			} else {
				card += tmp.charAt(i);
			}
		}
		return card;
	};

	initBankError = () => {
		let id = this.props.bankId;
		return !BackCardUtil.checkBankCard(id);
	};


	getCode() {
		if (this.codeEnable) {
			let self = this;
			showLoading('');
			this.props.getCode(this.props.token, function() {
				var time = 0;
				hideLoading('');
				self.timer = setInterval(function() {
					var timenow = self.codeTime - time;
					if (timenow > 0) {
						self.setState({
							savesecond: timenow + '秒'
						});
						self.codeEnable = false;
					} else {
						self.timer && clearInterval(self.timer);
						self.codeEnable = true;
						self.setState({
							savesecond: '发送验证码'
						});
						time = 0;
					}
					time++;
				}, 1000);
			});
		}
	}

	componentWillUnmount() {
		this.timer && clearInterval(this.timer);
	}

	save() {

		if (this.state.code == '' || this.state.code == undefined) {
			toast('请输入验证码');
			return;
		}

		if (this.state.bankid == '' || this.state.bankid == undefined) {
			toast('请输入银行卡号');
			return;
		}

		let card = this.state.bankid.replace(/\s+/g, "");

		const params = {
			token: this.props.token,
			type: 1,
			accountName: this.props.authName,
			bankId: card,
			bankName: this.state.bankname,
			bankDetail: this.props.bankDetail,
			code: this.state.code,
			city: this.state.bankarea,
			recordAccountId: this.props.recordAccountId
		};
		let self = this;
		this.props.saveBankInfo(this.flag, params, function() {
			if (self.flag == 'add') {
				toast("添加成功")
			} else {
				toast("修改成功")
			}
			self.props.naviBack();
		});
	}


	getBankInfo = () => {
		let self = this;
		let card = this.state.bankid.replace(/\s+/g, "");
		BankInfoCheckAction(this.props.authName, card, this.props.ownerCardNumber, this.state.bankphone, (data) => {
			if (data.showapi_res_code == 0) {
				let body = data.showapi_res_body;
				if (body.ret_code == 0) {
					let belong = body.belong;
					let area = belong.area;
					let bankName = belong.bankName;
					self.setState({
						bankname: bankName,
						bankarea: area
					})
				} else {
					let errorinfo = body.error;
					toast(errorinfo);
				}
			}
		});
	};


	checkCard = (txt) => {
		let op = "";
		let tmp = txt.replace(/\D/g, "");
		for (let i = 0; i < tmp.length; i++) {
			if (i % 4 === 0 && i > 0) {
				op += "  " + tmp.charAt(i);
			} else {
				op += tmp.charAt(i);
			}
		}
		let carderr = BackCardUtil.checkBankCard(txt);
		this.setState({
			bankid: op,
			carderror: !carderr
		});

		if (carderr) {
			this.getBankInfo();
		}
	};

	/***
	 * city
	 code
	 shen
	 shi
	 xian
	 */
	chageCity = () => {
		let self = this;
		ChooseCity(function(res) {
			let shen = res.shen;
			let shi = res.shi;
			let xian = res.xian;
			let temparea = "";
			if (shen != "" && shen != null && shen != undefined) {
				temparea += shen;
			}
			if (shi != "" && shi != null && shi != undefined) {
				temparea += " - " + shi;
			}
			if (xian != "" && xian != null && xian != undefined) {
				temparea += " - " + xian
			}
			self.setState({
				bankarea: temparea
			});
		})
	};

	/**
	 * 选择支行信息
	 */
	chooseBankDetail = () => {
		if (this.state.bankarea == '' || this.state.bankarea == undefined || this.state.bankarea == '开户地址') {
			toast('请先选择开户地址');
			return;
		}


		let shen = "";
		let shi = "";
		let xian = "";

		let areas = this.state.bankarea.split("-");
		shen = areas[0].replace(/\s+/g, "");
		shi = areas[1].replace(/\s+/g, "");
		if (areas.length == 3) {
			xian = areas[2].replace(/\s+/g, "");
		}

		let params = {
			bankName: this.state.bankname,
			area: {
				shen: shen,
				shi: shi,
				xian: xian
			}
		};

		this.props.naviPush("ChooseBank", params);
	};

	render() {
		let errorView;
		if (this.state.carderror) {
			errorView = (
				<TouchableOpacity onPress={() => Alert.alert('温馨提醒', '请输入正确的银行卡号')}>
                    <Image source={require('../../image/img_error.png')}
                           style={{width: 18, height: 18, marginRight: 5}}/>
                </TouchableOpacity>);
		}

		let cardnum = '';
		let len = this.props.ownerCardNumber.length;
		if (this.props.ownerCardNumber.length > 0) {
			cardnum = this.props.ownerCardNumber.substring(0, 4);
			cardnum += "**********";
			cardnum += this.props.ownerCardNumber.substring(len - 4, len);
		}

		return (
			<ScrollView style={{backgroundColor: '#ebebeb'}}>
                <View>
                    <Text style={{marginLeft: 10, marginTop: 12, marginBottom: 5}}>持卡人信息</Text>
                    <View style={{backgroundColor: 'white', flexDirection: 'column'}}>
                        <View style={commonStyles.itembar1}>
                            <Image source={require('../../image/card_user.png')}
                                   style={{width: 28, height: 28, marginRight: 10}}/>
                            <Text style={{}}>{this.props.authName}</Text>
                        </View>
                        <View style={commonStyles.line_gray}/>
                        <View style={commonStyles.itembar1}>
                            <Image source={require('../../image/card_id.png')}
                                   style={{width: 28, height: 28, marginRight: 10}}/>
                            <Text>{cardnum}</Text>
                        </View>
                    </View>
                    <View style={{height: 20, width: 1}}/>
                    <Text style={{marginLeft: 10, marginTop: 5, marginBottom: 5}}>银行卡信息</Text>
                    <View style={{backgroundColor: 'white', flexDirection: 'column'}}>
                        <View style={commonStyles.itembar1}>
                            <Image source={require('../../image/card_bankid.png')}
                                   style={{width: 28, height: 28, marginRight: 10}}/>
                            <TextInput
                                style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
                                placeholder="请输入银行卡号"
                                keyboardType='number-pad'
                                writingDirection='rtl'
                                underlineColorAndroid={'transparent'}
                                returnKeyType='next'
                                onChangeText={(text) => this.checkCard(text)}
                                value={this.state.bankid}
                                multiline={false}
                            />
                            {errorView}
                        </View>
                        <View style={commonStyles.line_gray}/>
                        <TouchableOpacity onPress={() => this.getBankInfo()}>
                            <View style={commonStyles.itembar1}>
                                <Image source={require('../../image/card_bank.png')}
                                       style={{width: 28, height: 28, marginRight: 10}}/>
                                <Text style={{
                                    flex: 1,
                                    alignItems: 'center',
                                    justifyContent: 'center'
                                }}>{this.state.bankname}</Text>
                            </View>
                        </TouchableOpacity>
                        <View style={commonStyles.line_gray}/>
                        <TouchableOpacity onPress={() => this.chageCity()}>
                            <View style={commonStyles.itembar1}>
                                <Image source={require('../../image/card_area.png')}
                                       style={{width: 28, height: 28, marginRight: 10}}/>
                                <Text style={{
                                    flex: 1,
                                    alignItems: 'center',
                                    justifyContent: 'center'
                                }}>{this.state.bankarea}</Text>
                                <Image style={{width: 20, height: 15}}
                                       source={require('../../image/img_right_grey.png')}/>
                            </View>
                        </TouchableOpacity>

                        <View style={commonStyles.line_gray}/>
                        <TouchableOpacity onPress={() => this.chooseBankDetail()}>
                            <View style={commonStyles.itembar1}>
                                <Image source={require('../../image/card_bank1.png')}
                                       style={{width: 28, height: 28, marginRight: 10}}/>
                                <Text style={{
                                    flex: 1,
                                    alignItems: 'center',
                                    justifyContent: 'center'
                                }}>{this.props.bankDetail.length == 0 ? "开户支行" : this.props.bankDetail}</Text>
                                <Image style={{width: 20, height: 15}}
                                       source={require('../../image/img_right_grey.png')}/>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={{height: 20, width: 1}}/>
                    <Text style={{marginLeft: 10, marginTop: 5, marginBottom: 5}}>短信验证</Text>
                    <View style={{backgroundColor: 'white', flexDirection: 'column'}}>
                        <View style={commonStyles.itembar}>
                            <Image source={require('../../image/card_code.png')}
                                   style={{width: 28, height: 28, marginRight: 10}}/>
                            <TextInput
                                style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
                                placeholder="验证码"
                                keyboardType='number-pad'
                                writingDirection='rtl'
                                underlineColorAndroid={'transparent'}
                                returnKeyType='next'
                                onChangeText={(text) => this.setState({
                                    code: text,
                                })}
                                value={this.state.code}
                                multiline={false}
                            />
                            <TouchableHighlight
                                onPress={() => this.getCode()}
                                underlayColor='rgba(255,255,255,0)'>
                                <View style={[commonStyles.codebtn, {width: 100}]}>
                                    <Text style={commonStyles.greenbtn_txt}>{this.state.savesecond}</Text>
                                </View>
                            </TouchableHighlight>
                        </View>
                    </View>
                    <View style={{height: 20, width: 1}}/>
                    <TouchableHighlight
                        onPress={() => this.save()}
                        underlayColor='rgba(255,255,255,0)'>
                        <View style={[commonStyles.greenbtn, {marginTop: 15}]}>
                            <Text style={commonStyles.greenbtn_txt}>保存</Text>
                        </View>
                    </TouchableHighlight>
                </View>
            </ScrollView>
		);
	}
}

const mapStateToProps = state => ({
	token: state.mainmodel.token,
	accountName: state.income.accountName,
	bankId: state.income.bankId,
	bankArea: state.income.bankArea,
	bankName: state.income.bankName,
	bankDetail: state.income.bankDetail,
	accountId: state.income.accountId,
	recordAccountId: state.income.recordAccountId,
	authName: state.shop.authName,
	ownerCardNumber: state.shop.ownerCardNumber,
});

const mapDispatchToProps = (dispatch) => {
	return {
		getCode: (token, success) => {
			dispatch(getCodeAction(token, success));
		},
		saveBankInfo: (flag, params, success) => {
			dispatch(saveBankInfoAction(flag, params, success));
		},
		naviPush: (routeName, params) => {
			dispatch(naviPush(routeName, params))
		},
		naviBack: (routeName) => {
			dispatch(naviBack(routeName))
		},
	}
};

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(AccountEdit);